﻿using System;
using System.IO;
using System.Net;
using System.Net.Browser;
using System.Runtime.InteropServices.Automation;

namespace SilverlightWebcamEncoder.Helpers
{
    public class YouTubeFileUpload
    {
        private readonly string m_installationPath;
        private dynamic m_uploader;
        private const string CLR_PROXY_PROGID = "ClrProxy";
        private const string ENCODER_ASSEMBLY_NAME = "Desktop.Media.Encoder.dll";
        private const string UPLOADER_CLASS_NAME = "Desktop.Media.Encoder.YouTubeUploader";

        public YouTubeFileUpload(string installationPath)
        {
            m_installationPath = installationPath;
            CreateUploader();
        }
         
        public void Upload(string username, string password, string title, string filepath)
        {
            m_uploader.Upload(username, password, title, filepath);
        }

        public bool Failed
        {
            get
            {
                return m_uploader.Failed;
            }
        }

        public bool Completed
        {
            get
            {
                return m_uploader.Completed;       
            }
        }

        private void CreateUploader()
        {
#if SL4BETA
            dynamic fullDotNetProxy = ComAutomationFactory.CreateObject(CLR_PROXY_PROGID);
#else
            dynamic fullDotNetProxy = AutomationFactory.CreateObject(CLR_PROXY_PROGID);
#endif
            string fullAssemblyPath = Path.Combine(m_installationPath, ENCODER_ASSEMBLY_NAME);
            dynamic assembly = fullDotNetProxy.GetAssembly(fullAssemblyPath);
            dynamic youTubeUploaderType = fullDotNetProxy.GetDotNetType(assembly, UPLOADER_CLASS_NAME);
            m_uploader = fullDotNetProxy.CreateInstance(youTubeUploaderType);
        }
    }
}
